package yc.bluetooth.libvoice.play;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 作者：yeqianyun on 2020/3/20 14:20
 * 邮箱：1612706976@qq.com
 *
 * 播放解码后的音频.wav格式
 */
public class VoicePlay implements MediaPlayer.OnCompletionListener {
    private static final String TAG = VoicePlay.class.getSimpleName();

    private MediaPlayer mMediaPlayer;
    private String localAudioFilePath;

    public VoicePlay() {
    }

    public void setLocalAudioFilePath(String localAudioFilePath) {
        this.localAudioFilePath = localAudioFilePath;
    }

    /**
     * 播放
     */
    public void start(){
        if(mMediaPlayer == null){
            mMediaPlayer = new MediaPlayer();
        }
        if(!mMediaPlayer.isPlaying()) {
            Log.d(TAG, "localAudioFilePath = " + localAudioFilePath);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(this);
            try {
                File tempFile = new File(localAudioFilePath);
                FileInputStream fis = new FileInputStream(tempFile);
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(fis.getFD());

                mMediaPlayer.setVolume(1.0f, 1.0f);
                mMediaPlayer.setLooping(false);
                mMediaPlayer.prepare();
                //开始播放
                mMediaPlayer.start();
                Log.d(TAG, "开始播放...");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 停止播放
     */
    public void stop(){
        if (mMediaPlayer != null){
            if (mMediaPlayer.isPlaying()){
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    //音频播放结束
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if(mediaPlayer == null){
            return;
        }

        Log.d(TAG, "播放结束");
        if(onPlayStateListener != null){
            onPlayStateListener.onPlayCompletion();
        }
    }


    private OnPlayStateListener onPlayStateListener;
    public void setOnPlayStateListener(OnPlayStateListener onPlayStateListener) {
        this.onPlayStateListener = onPlayStateListener;
    }
    public interface OnPlayStateListener{
        void onPlayCompletion();
    }
}
